package cn.quevo.spring.util;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SpringUtil {
	private static Logger log = LoggerFactory.getLogger(SpringUtil.class);
	
	private static ApplicationContext applicationContext = null;
	
	/**
	 * 通过beanName获取spring管理的bean
	 * 
	 * @author July july_sky@foxmail.com
	 * @date 2016年10月12日上午11:13:11
	 * @param name
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {
		checkApplicationContext();
		return (T) applicationContext.getBean(name);
	}
	
	/**
	 * 根据class获取spring管理的bean
	 * @author July july_sky@foxmail.com
	 * @date 2016年10月12日上午11:13:11
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(Class<T> clazz) {
		checkApplicationContext();
		return (T) applicationContext.getBeansOfType(clazz);
	}

	/**
	 * 检验ApplicationContext是否成功注入
	 * 
	 * @author July july_sky@foxmail.com
	 * @date 2016年10月12日上午11:13:11
	 */
	public static boolean checkApplicationContext() {
		if (getApplicationContext() == null) {
			log.info("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
			throw new IllegalStateException(
					"applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
		}
		return true;
	}

	/**
	 * 初始化
	 * 
	 * @author July july_sky@foxmail.com
	 * @date 2016年10月12日上午11:13:11
	 * @param applicationContext
	 */
	public static void setApplicationContext(ApplicationContext applicationContext){
		SpringUtil.applicationContext = applicationContext;
	}

	public static ApplicationContext getApplicationContext() {
		if(applicationContext == null){
			applicationContext = WebApplicationContextUtils.getWebApplicationContext(WebUtils.getHttpServletRequest().getServletContext());
		}
		return applicationContext;
	}
	
	public static ApplicationContext getApplicationContext(ServletContext servletContext) {
		applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		return applicationContext;
	}
}
